<template>
  <ol class="list" ref="list">
    <li
      v-for="item in letters"
      :key="item"
      :ref="item"
      @touchstart.prevent="hdLetterStart"
      @touchend="hdLetterEnd"
      @touchmove="hdLetterMove"
      @click="hdLetterClick"
    >
      {{ item }}
    </li>
  </ol>
</template>

<script>
export default {
  name: 'Alphabet',
  props: ['cities'],
  computed: {
    letters() {
      return Object.keys(this.cities)
    },
  },

  data() {
    return {
      isTouched: false, // 判断鼠标是否按下移动的钩子
      listWrapY: 0, // 字母表 y 坐标
      disY: 0, // 移动差值
      startLetter: '', // 起始字母
      startY: 0, // 起始 y 坐标
      startIndex: 0,
      letterHeight: 0,
      currentLetter: '',
    }
  },

  methods: {
    // 点击
    // 拿到当前字母，把字母传递给 List 组件
    // List 中匹配字母，然后 better-scrolll 定位到这个字母位置

    // 同时拿到当前鼠标位置、字母表位置、单个字母高度
    // 用来配合 move 事件
    hdLetterStart(e) {
      this.isTouched = true
      this.startLetter = e.target.innerText
      this.letterHeight = e.target.offsetHeight
      this.startY = e.touches[0].clientY
      this.lettersWrapY = this.$refs['A'][0].offsetTop
      this.startIndex = this.letters.findIndex((item) => item === this.startLetter)
    },

    hdLetterClick() {
      this.$bus.$emit('hdGetLetter', this.startLetter)
    },

    hdLetterEnd() {
      this.isTouched = false
    },

    hdLetterMove(e) {
      if (this.isTouched) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.disY = e.touches[0].clientY - this.startY
          let miniIndex = 0
          let maxIndex = this.letters.length - 1
          let currentIndex = Math.round(this.disY / this.letterHeight) + this.startIndex
          if (currentIndex < miniIndex) {
            currentIndex = miniIndex
          }
          if (currentIndex > maxIndex) {
            currentIndex = maxIndex
          }
          this.currentLetter = this.letters[currentIndex]
          console.log(Math.round(this.disY / this.letterHeight) + this.startIndex)
          this.$bus.$emit('hdGetLetter', this.currentLetter)
        }, 16)
      }
    },
  },

  mounted() {},
}
</script>

<style lang="scss" scoped>
.list {
  position: fixed;
  z-index: 8;
  right: 0;
  top: 1rem;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  li {
    width: 0.6rem;
    line-height: 0.5rem;
    color: $bg;
    text-align: center;
    touch-action: none;
    font-size: 0.32rem;
  }
}
</style>
